package com.avicit.zipkinkafkaesserver.controller;

import com.avicit.zipkinkafkaesserver.dao.es.entity.ZipkinInterfaceAverageDurationES;
import com.avicit.zipkinkafkaesserver.entity.ZipkinInterfaceAverageDuration;
import com.avicit.zipkinkafkaesserver.entity.ZipkinInterfaceCount;
import com.avicit.zipkinkafkaesserver.service.ZipkinInterfaceAverageDurationService;
import com.avicit.zipkinkafkaesserver.vo.InterfaceCountVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 平均耗时统计
 */
@Controller
public class ZipkinInterfaceAverageDurationController {

    @Autowired
    private ZipkinInterfaceAverageDurationService service;


    @GetMapping("api/interfaceDurationCount")
    public String query(
            long startTime, long endTime,
            Model model,
            @RequestParam(required = false, defaultValue = "0") long min,
            @RequestParam(required = false, defaultValue = "0") long max,
            @RequestParam(required = false, defaultValue = "0") int topN
    ) {
        List<ZipkinInterfaceAverageDurationES> query = service.query(startTime, endTime, min, max, topN);

        List<InterfaceCountVo> collect = query.stream().map(item -> {
            long interfaceAverageDuration = item.getInterfaceAverageDuration();
            InterfaceCountVo build = InterfaceCountVo
                            .builder()
                            .ip(item.getInterfaceIp())
                            .serverName(item.getServerName())
                            .interfaceName(item.getInterfacePath())
                            .duration((int) interfaceAverageDuration)
                            .build();
                    return build;
                }

        ).collect(Collectors.toList());
        model.addAttribute("countVos",collect);
        return "apiInterfaceDurationCount";
    }

    @GetMapping("/api/interfaceAvgDuration/v2")
    public String interfaceAvgDuration(@RequestParam(required = false) String queryDate,
                                    Model model
    ) {
        List<ZipkinInterfaceAverageDuration> interfaceCountList = service.interfaceAvgDuration(queryDate);
        model.addAttribute("countVos",interfaceCountList);
        return "interfaceAvgDuration";
    }
}
